import Vue from 'vue'
import VueRouter from 'vue-router'

const Home = () => import('../views/home/Home.vue');
const Category = () => import('../views/category/Category.vue');
const Cart = () => import('../views/cart/Cart.vue');
const Profile = () => import('../views/profile/Profile.vue');
const Detail = () => import('../views/detail/Detail.vue');
const NotFound = () => import('../views/notFount/NotFound.vue');

// 通过Vue.use(插件)，安装插件
Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    meta: {
      title: '首页',
      showTab: true
    },
    component: Home
  },
  {
    path: '/category',
    name: 'category',
    meta: {
      title: '分类',
      showTab: true
    },
    component: Category
  },
  {
    path: '/cart',
    name: 'cart',
    meta: {
      title: '购物车',
      showTab: true
    },
    component: Cart
  },
  {
    path: '/profile',
    name: 'profile',
    meta: {
      title: '我的',
      showTab: true
    },
    component: Profile
  },
  {
    path: '/detail/:iid',
    name: 'detail',
    meta: {
      title: '详情页',
      showTab: false
    },
    component: Detail
  },
  {
    path: '*',
    name: 'notFound',
    meta: {
      title: '404',
      showTab: true
    },
    component: NotFound
  }
];

//解决vue-router重复点击报错问题（this.$router.replace()）
const originalReplace= VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err);
};

//解决vue-router重复点击报错问题（this.$router.push()）
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push= function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

const router = new VueRouter({
  routes,
  mode: 'history',
  linkActiveClass: 'active'
});

router.beforeEach((to, from, next) => {
  document.title =  to.matched[0].meta.title;
  next()
});

export default router
